import { AssetManager, assetManager, ImageAsset, SpriteFrame } from "cc";
import { BCGameLog } from "../utils/BCGameLog";

export class BCResourcesMgr {
	public static getResWithPath(path: string, resType: any): Promise<any> {
		return new Promise((resolve, reject) => {
			assetManager.loadAny({ 'path': path, "bundle": "resources", "type": resType }, (err, assets) => {
				if (err) {
					BCGameLog.error("[ResourcesMgr]", `Load resources:[${path}] error`);
					reject();
					return;
				}
				resolve(assets);
			});
		});
	}

	public static getFrameWithUrl(url: string): Promise<SpriteFrame>{
		if (!url || url.length < 0) {
			return null;
		}
		return new Promise((resolve, reject) => {
			assetManager.loadRemote(url, { ext: '.png' }, (err, asset: ImageAsset) => {
				if (err) {
					BCGameLog.warn("[ResourcesMgr]", "LoadFrameWithUrl Faield: " + url);
					reject();
					return;
				}
				const frame = SpriteFrame.createWithImage(asset);
				frame.packable = false;
				resolve(frame);
			});
		});
	}

	public static loadGameBundle(gameName: string): Promise<AssetManager.Bundle>{
		return new Promise((resolve, reject)=>{
			assetManager.loadBundle(gameName, null, (error: Error, bundle: AssetManager.Bundle) => {
				if (error) {
					BCGameLog.error("[ResourcesMgr]", "Load bundle failed:", gameName);
					reject();
					return;
				}
				resolve(bundle);
			});
		});
	}

	public static getBundleResWithPath(bundleName: string, path: string, resType: any): Promise<any>{
		return new Promise((resolve, reject) => {
			const bundle = assetManager.getBundle(bundleName);
			if(!bundle){
				BCGameLog.error("[ResourcesMgr]", `没有找到bundle:[${bundleName}]，请先加载`);
				return;
			}
			bundle.load(path, resType, (err: Error, assets: any) => {
				if (err) {
					BCGameLog.error("[ResourcesMgr]", `Load bundle:[${bundleName}] resources:[${path}] error`);
					reject();
					return;
				}
				resolve(assets);
			});
		});
	}

	public static releaseBundle(bundleName: string){
		const bundle = assetManager.getBundle(bundleName);
		bundle && assetManager.removeBundle(bundle);
	}
}

